local factory = require "bw.orm.factory"
local log     = require "bw.log"
local mongo   = require "db.mongo"

local users = {} -- acc -> user

local M = {}

local function save_user(acc)
    local user = users[acc]
    if not user then
        log.errorf("save_user error, user not exist, acc:%s", acc)
        return
    end
    mongo.update("user", {acc = acc}, user)
end

local function load_user(acc)
    local user = mongo.find_one("user", {acc = acc}, {_id = false})
    if not user then
        user = factory.create_obj("User", {acc = acc})
        mongo.insert("user", user)
    end
    users[acc] = user
    return user
end

function M.get_user(acc)
    local user = users[acc]
    if not user then
        user = load_user(acc)
    end
    return user
end

function M.set_user(acc, k, v)
    local user = M.get_user(acc)
    if not user then
        log.errorf("set_user error, user not exist, acc:%s", acc)
        return
    end
    user[k] = v
    save_user(acc)
end

function M.get_user_kv(acc, k)
    local user = M.get_user(acc)
    if not user then
        log.errorf("get_user_kv error, user not exist, acc:%s", acc)
        return
    end
    return user.kv[k]
end

function M.set_user_kv(acc, k, v)
    local user = M.get_user(acc)
    if not user then
        log.errorf("set_user_kv error, user not exist, acc:%s", acc)
        return
    end
    user.kv[k] = v
    log.debug("set_user_kv", user)
    save_user(acc)
end

return M
